package com.sinog.front.service.azbj.background;

import com.sinog.core.domain.Background;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.IdGen;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.feign.biz.BackgroundFeignService;
import com.sinog.front.feign.biz.FtpUtilService;
import com.sinog.front.service.azbj.uploadappendix.AsyncUploadFileToFtp;
import com.sinog.front.service.user.UserFacade;
import com.sinog.front.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @desc 系统管理 - 更换背景 - 更换背景 - 背景图片附件上传类
 * @author -
 * @date -
 */
@Slf4j
@Service
public class BackgroundDealFileService {

    private static final Pattern COMPILE = Pattern.compile("@@@@@",Pattern.LITERAL);
    @Resource
    private BackgroundFeignService backgroundFeignService;
    @Autowired
    private UserFacade userFacade;
    @Autowired
    private AsyncUploadFileToFtp asyncUploadFileToFtp;
    @Resource
    private FtpUtilService ftpUtilService;

    /**
     * 系统管理 - 更换背景 - 更换背景 - 上传背景图片
     * @param file file
     * @param longUser longUser
     * @param backgroundName backgroundName
     * @return Result
     */
    public Result uploadBackgroundFile(MultipartFile file,String longUser,String backgroundName) {
        String fileName = file.getOriginalFilename();
        long genId = IdGen.get().next();
        fileName = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(File.separator) + 1);
        String tempFileName = longUser + File.separator + genId + fileName.substring(fileName.lastIndexOf('.'));
        String filePath = FileUtil.getUploadFilePath() + tempFileName;
        File desFile = new File(filePath);
        if(!desFile.getParentFile().exists()) {
            try {
                desFile.getParentFile().mkdirs();
            } catch(RuntimeException e) {
                log.error(e.getMessage());
            }
        }
        //上传文件到ftp
        try {
            file.transferTo(desFile);
            // 获取ftp上传下载路径
            String datapath = ftpUtilService.getFtpClient().get("datapath");
            asyncUploadFileToFtp.uploadFileToFtp(datapath + userFacade.getAuthentication().getAccount(),filePath);
        } catch(IOException e) {
            log.error("发生异常:{}",e.getMessage());
        }
        Background background = new Background();
        background.setUserId(longUser);
        background.setUploadFileName(fileName);
        background.setBackgroundName(backgroundName);
        background.setServerUrl(tempFileName);
        background.setIsUsed("0");
        background.setIsDefault("0");
        background.setCreateUser(longUser);
        background.setUpdateUser(longUser);
        Date date = new Date();
        background.setCreateTime(date);
        background.setUpdateTime(date);
        int result = backgroundFeignService.saveBackgroundFileData(background);
        if(Constants.Number.NUM_ZERO < result) {
            return Result.success("上传成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED,"上传失败");
    }

    /**
     * 系统管理 - 更换背景 - 更换背景 - 删除上传文件
     * 逻辑：ftp有文件：1、先删ftp图片 2、再删本地图片 3、最后删数据
     * ftp没文件：1、先删本地图片，2、最后删数据
     * @param id id
     * @param fileUrl fileUrl
     * @param account account
     * @return Result
     */
    public Result deleteBackgroundFileOne(String id,String account,String fileUrl) {
        Background background = new Background();
        background.setUserId(account);
        background.setId(Integer.parseInt(id));
        //查询是否有该数据
        Background background1 = backgroundFeignService.findBackgroundFileOne(background);
        if(null == background1) {
            return Result.failure(ReturnCode.DELETE_FILL_FAILED);
        }
        boolean ftpFileDelFlag;
        String uploadFilePath = FileUtil.getUploadFilePath();
        File file = new File(uploadFilePath + fileUrl);
        try {
            //1、先删ftp图片 2、再删本地图片 3、最后删数据
            String absolutePath = file.getAbsolutePath();
            absolutePath = COMPILE.matcher(absolutePath).replaceAll(Matcher.quoteReplacement(File.separator));
            String[] fileUrlArr = absolutePath.split(Matcher.quoteReplacement(File.separator));
            // 获取ftp上传下载路径
            String datapath = ftpUtilService.getFtpClient().get("datapath");
            try {
                ftpFileDelFlag = backgroundFeignService.removeBackgroundFromFtp(datapath + fileUrlArr[fileUrlArr.length - 1],fileUrlArr);
                //ftp文件删除成功，删除本地文件
                if(ftpFileDelFlag) {
                    file = new File(absolutePath);
                    boolean delLocalFileFlag = file.delete();
                    //本地文件删除成功，删除数据库记录
                    if(delLocalFileFlag) {
                        //如果有删除
                        int result = backgroundFeignService.removeBackgroundFileOne(background);
                        if(Constants.Number.NUM_ZERO < result) {
                            return Result.success("删除成功！");
                        }
                    }
                }
            } catch(Exception e) {
                log.error("发生异常:{}",e.getMessage());
            }
            //本地存在文件逻辑
            file = new File(absolutePath);
            boolean localFileExists = file.exists();
            //本地存在图片
            if(localFileExists) {
                boolean delLocalFileFlag = file.delete();
                //本地文件删除成功，删除数据库记录
                if(delLocalFileFlag) {
                    //如果有删除
                    int result = backgroundFeignService.removeBackgroundFileOne(background);
                    if(Constants.Number.NUM_ZERO < result) {
                        return Result.success("删除成功！");
                    }
                }
            }
        } catch(RuntimeException e) {
            log.error("发生异常:",e);
        }
        return Result.failure(ReturnCode.DELETE_FILL_FAILED);
    }
}